// 页面初始化是获取ztree
function generateTree() {
    $.ajax({
        "url": "menu/get/whole/tree.json",
        "type": "post",
        "dataType": "json",
        "async": false,
        "success": function (response) {
            var result = response.result;
            if (result == "SUCCESS") {
                var setting = {
                    view: {
                        "addDiyDom": myAddDiyDom,
                        "addHoverDom": myAddHoverDom,
                        "removeHoverDom": myRemoveHoverDom
                    },
                    data: {
                        key: {
                            "url": "xiaojinhao"
                        }
                    }
                };
                var zNodes = response.data;
                // ztree初始化方法，将JSON对象包装到ztree中
                $.fn.zTree.init($("#treeDemo"), setting, zNodes);
            }
            if (result == "FAILED") {
                layer.msg(response.message);
            }
        }
    });
}


// 修改默认图标
function myAddDiyDom(treeId, treeNode) {

    // treeNode就是ztree的每个节点
    console.log(treeNode);

    // 根据每个节点中的tId属性，找到当前的spanId
    var spanId = treeNode.tId + "_ico";

    // 修改span的class属性就能修改每个节点的图标
    $("#" + spanId).removeClass().addClass(treeNode.icon);
}

// 为节点增加鼠标移入的效果
function myAddHoverDom(treeId, treeNode) {

    var anchorId = treeNode.tId + "_a";

    var btnGropId = treeNode.tId + "_btnGrop";

    // 将此节点的id动态绑定，this.id 可以获取到
    var addBtn = "<a id='" + treeNode.id + "' class='addBtn btn btn-info dropdown-toggle btn-xs' style='margin-left:10px;padding-top:0px;' href='#' title='添加节点'>&nbsp;&nbsp;<i class='fa fa-fw fa-plus rbg '></i></a>\n";
    var removeBtn = "<a id='" + treeNode.id + "' class='removeBtn btn btn-info dropdown-toggle btn-xs' style='margin-left:10px;padding-top:0px;' href='#' title='删除节点'>&nbsp;&nbsp;<i class='fa fa-fw fa-times rbg '></i></a>\n";
    var editBtn = "<a id='" + treeNode.id + "' class='editBtn btn btn-info dropdown-toggle btn-xs' style='margin-left:10px;padding-top:0px;' href='#' title='修改节点'>&nbsp;&nbsp;<i class='fa fa-fw fa-edit rbg '></i></a>";

    var level = treeNode.level;
    var addHtml = "";

    // 根据节点的level属性，决定显示哪些按钮
    if (level == 0) {
        addHtml = editBtn + addBtn;
    }
    if (level == 1) {
        addHtml = editBtn + addBtn;
        var chid = treeNode.children;
        if (chid.length == 0) {
            addHtml = editBtn + addBtn + removeBtn;
        }
    }
    if (level == 2) {
        addHtml = editBtn + removeBtn;
    }

    // 将要插入的图标放入span中，id为btnGroId ,当它的长度为0时，代表还未插入，此时才可以插入
    if ($("#" + btnGropId).length > 0) {
        return;
    }

    // 将span插入到要显示的位置
    $("#" + anchorId).after("<span id='" + btnGropId + "'>" + addHtml + "</span>");

}

// 为节点增加鼠标移出的效果
function myRemoveHoverDom(treeId, treeNode) {

    var btnGropId = treeNode.tId + "_btnGrop";
    // 清空显示按钮的span
    $("#" + btnGropId).remove();
}